﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdvanceLib.ScriptCore;
using AdvanceLib.ScriptCore.DebugCore;

namespace AdvanceLib.Extension.Root.DebugPasses
{
    public class SystemCommandConflictPass : CommandPass
    {
        #region Constructors
        public SystemCommandConflictPass(RootProvider provider)
        {
            this._host = provider.Host;
        }
        #endregion

        #region Fields
        private ScriptHost _host;
        #endregion

        #region CommandPass Members
        public override void Pass(DebugResult result, string input)
        {
            if (this.CurrentLinePartIndex == 0 &&
                this.CurrentLine.StartsWith(this._host.SystemCommandInitialization))
            {
                string commandName = input.Substring(this._host.SystemCommandInitialization.Length);

                if (this._host.ExtensionManager.HasSystemCommand(commandName))
                {
                    List<ISystemCommand> systemCommands = this._host.ExtensionManager.GetSystemCommandsByName(commandName);

                    if (systemCommands != null && systemCommands.Count > 1)
                    {
                        bool error = false;

                        foreach (ISystemCommand currentCommand in systemCommands)
                        {
                            if (error) break;
                            foreach (ISystemCommand compareCommand in systemCommands)
                            {
                                if (currentCommand != compareCommand)
                                {
                                    error = currentCommand.ExpectedParameters == compareCommand.ExpectedParameters;
                                }
                                if (error) break;
                            }
                        }

                        if (error)
                        {
                            result.Errors.Add(new DebugError()
                            {
                                Line = this.CurrentLineIndex,
                                Message = "FATAL ERROR: Systemcommand '" + commandName + "' exists multiple times."
                            });
                        }
                    }
                }
            }
        }
        #endregion
    }
}
